<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Orders extends Backend {

	public function __construct()
	{
		parent::__construct();
		$this->lang->load('sites');
		$this->load->model(['site_model','sitecategory_model','siteproduct_model','siteuser_model','siteorder_model','sf_model']);
		$this->data['page_home']  = lang('lang_dashboard');
		$this->data['page_title'] = lang('lang_order');
		
		$this->data['statetype']=[
			"1"=>'未付款',
			"2"=>'已付款',
			"3"=>'采购中',
			"4"=>'已发货',
			"5"=>'已完成',
			"6"=>'取消',
			"7"=>'退货',
			"8"=>'付款出错',
			"9"=>'ECHECK',
			"10"=>'BACKORDER'
		];
		$this->data['statelabel']=[
			"1"=>'label-danger',
			"2"=>'label-success',
			"3"=>'label-primary',
			"4"=>'label-info',
			"5"=>'label-info',
			"6"=>'label-warning',
			"7"=>'label-warning',
			"8"=>'label-danger',
			"9"=>'label-warning',
		];

	}

	private function makexlsx($data)
	{


		$spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet()->setTitle(date("Y-m-d").'询盘列表');

        $field=["站点名称","真实姓名","邮箱","电话","数量","留言","时间","ip地址","国家","来源"];
        $i=0;
        foreach ($field as $key => $value) {
            $sheet->getColumnDimension(num2alpha($i))->setAutoSize(true);
            $sheet->setCellValue(num2alpha($i).'1', $value);
            $i++;
		}
		$rowcount=1;
		if($data):
			foreach($data as $k=>$item)
			{
				$rowcount++;
				$v=[$item["siteid"],$item["realname"],$item["email"],$item["phone"],$item["quantity"],$item["info"],date("Y-m-d",strtotime($item["addtime"])),$item["ipaddr"],$item["country"],$item["url"]];
				$i=0;
				foreach($field as $key=>$value){
					$sheet->getCell(num2alpha($i++).$rowcount)->setValueExplicit(
						$v[$key],
                        \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
					);
				}

			}
		endif;

        $writer = new Xlsx($spreadsheet);        
        $filename=date("Y-m-d.H/i/s")."询盘列表.xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
		$writer->save('php://output');		
		die();
	}
	
	public function index()
	{
		// Title
		$this->data['meta_title'] = $this->data['page_title'];

		// Breadcrumbs
		$this->data['array_breadcrumbs'] = array(
			$this->data['page_home']  => 'backend',
			'所有询盘'=>'backend/orders'
		);

		$config = $this->systemconfig_model->get_configs(); 
		$this->data['config']=$config;

		$key=trim($this->input->get('keyword'));
		if(substr($key, -1)==">")
		{
			$key=substr($key,0,-1);
		}
		
		$page=max(1,(int) $this->input->get('page'));
		$sitetype=intval($this->input->get('sitetype'));
		$shopfrom=trim($this->input->get('shopfromm'));		
		$pagesize=intval($this->input->get('pagesize'));		
		$timelimit=$this->input->get("timelimit");

        if($pagesize){
            set_cookie("pagesize",$pagesize,60*60*24);
        }else{
            $pagesize=get_cookie("pagesize");
		}
		$this->data['sindex']=$this->site_model->get_name_index();

		$siteid=[];
		if($key)
		{
			foreach($this->data['sindex'] as $k=>$v)
			{
				if(strstr(strtolower($v),strtolower($key)))
				{
					$siteid[]=$k;
				}
			}
			if(count($siteid)>0)
			{
				$key="";
			}
		}
		if($sitetype>0)
		{
			$sites=$this->site_model->getsitetype($sitetype);
			if($sites)
			{
				$siteid=[];
				foreach($sites as $s)
				{
					$siteid[]=$s["id"];
				}
			}
		}
		$spsite=[];
		$spsites=[];
		$shopifysite=$this->site_model->getallsync();
		if($shopifysite):
		foreach($shopifysite as $ac)
		{
			$spsite[]=$ac["id"];
			$spsites[$ac["id"]]=$ac;
		}
		endif;
		$this->data['spsite']=$spsite;
		$this->data['spsites']=$spsites;   

		$state= 0;
		$siteid=(int) $this->input->get('state');
		$except=(int) $this->input->get('except');

		$export=intval($this->input->get('export'));
		if($export==1)
		{
			$orders=$this->siteorder_model->getbyfilter($siteid,$key,0,$state,$timelimit,$except,$shopfrom);
			foreach ($orders as $k=>$v ){
                $v = $this->site_model->get_name_by_id($orders[$k]['siteid']);
			    $orders[$k]['siteid'] = $v['name'];
            }
			$this->makexlsx($orders);
		}
		$page_data=$this->siteorder_model->getpage($siteid,$page,$pagesize,$key,0,$state,$timelimit,$except,$shopfrom);
		$this->data['loglist']=$page_data["data"];
		$this->data['pager']=$page_data["pager"]; 
		$this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
		$this->data['page']=$page;   
		$this->data['sitetype'] = $this->config->item('site_types');
		$this->data['state']=$state;   
		$this->data['shopfrom']=$shopfrom;
		$this->data['cdmap']= $this->sf_model->getcdmap();

		
		$keyword = array(
			'name'      => 'keyword',
			'id'        => 'keyword',
			'value'     =>  $key,
			'class'     =>  'form-control input-sm',
			'placeholder'=> '快速查询关键字',
			'maxlength' => '100'
		);
		$this->data['keyword']=$keyword;
        $this->data['content_header_title'] = content_header_title($this->data['page_title'],'订单');
		$this->data['content'] = 'orders2';

		$this->render();
	}

	public function ordersmobileget()
    {
        $config = $this->systemconfig_model->get_configs();
        $this->data['config']=$config;

        $key=trim($this->input->get('keyword'));
        if(substr($key, -1)==">")
        {
            $key=substr($key,0,-1);
        }

        $page=max(1,(int) $this->input->get('page'));
        $sitetype=intval($this->input->get('sitetype'));
        $shopfrom=trim($this->input->get('shopfromm'));
        $pagesize=intval($this->input->get('pagesize'));
        $timelimit=$this->input->get("timelimit");

        if($pagesize){
            set_cookie("pagesize",$pagesize,60*60*24);
        }else{
            $pagesize=get_cookie("pagesize");
        }
        $this->data['sindex']=$this->site_model->get_name_index();

        $siteid=[];
        if($key)
        {
            foreach($this->data['sindex'] as $k=>$v)
            {
                if(strstr(strtolower($v),strtolower($key)))
                {
                    $siteid[]=$k;
                }
            }
            if(count($siteid)>0)
            {
                $key="";
            }
        }
        if($sitetype>0)
        {
            $sites=$this->site_model->getsitetype($sitetype);
            if($sites)
            {
                $siteid=[];
                foreach($sites as $s)
                {
                    $siteid[]=$s["id"];
                }
            }
        }
        $spsite=[];
        $spsites=[];
        $shopifysite=$this->site_model->getallsync();
        if($shopifysite):
            foreach($shopifysite as $ac)
            {
                $spsite[]=$ac["id"];
                $spsites[$ac["id"]]=$ac;
            }
        endif;
        $this->data['spsite']=$spsite;
        $this->data['spsites']=$spsites;

        $state= 0;
        $siteid=(int) $this->input->get('state');
        $except=(int) $this->input->get('except');

        $export=intval($this->input->get('export'));
        if($export==1)
        {
            $orders=$this->siteorder_model->getbyfilter($siteid,$key,0,$state,$timelimit,$except,$shopfrom);
            foreach ($orders as $k=>$v ){
                $v = $this->site_model->get_name_by_id($orders[$k]['siteid']);
                $orders[$k]['siteid'] = $v['name'];
            }
            $this->makexlsx($orders);
        }
        $page_data=$this->siteorder_model->getpage($siteid,$page,$pagesize,$key,0,$state,$timelimit,$except,$shopfrom);
        $this->data['loglist']=$page_data["data"];
        $this->data['pager']=$page_data["pager"];
        $this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
        $this->data['page']=$page;
        $this->data['sitetype'] = $this->config->item('site_types');
        $this->data['state']=$state;
        $this->data['shopfrom']=$shopfrom;
        $this->data['cdmap']= $this->sf_model->getcdmap();


        $keyword = array(
            'name'      => 'keyword',
            'id'        => 'keyword',
            'value'     =>  $key,
            'class'     =>  'form-control input-sm',
            'placeholder'=> '快速查询关键字',
            'maxlength' => '100'
        );
        $this->data['keyword']=$keyword;
        $this->data['content_header_title'] = content_header_title($this->data['page_title'],'订单');
        $this->data['content'] = 'orders2';

        print_r(json_encode($page_data["data"]));
    }

    public function ordersajaxdel()
    {
        $return=["status"=>1];
        $id=$this->input->post("cid");
        $newdata['state'] = '-1';
        $this->siteorder_model->update($id,$newdata);
        echo json_encode($return);
        die();
    }

	function seturl()
	{
		$oid=$this->input->get("oid");
		$rid=$this->input->get("rid");
		$url=$this->input->get("url");
		if($oid && $rid && $url)
		{
			$order=$this->siteorder_model->getitembyid($oid);
			if($order)
			{
				$where=' siteid='.$order["siteid"]." and (productinfo like '%\"rid\":\"{$rid}\"%' or productinfo like '%\"rid\":{$rid},%')";
				$uporders=$this->siteorder_model->getfilter($where);
				if($uporders)
				{
					foreach($uporders as $po)
					{
						$productinfo=json_decode($po["productinfo"],true);
						foreach($productinfo as &$pro)
						{
							if($pro["rid"]==$rid)
							{
								$pro["url"]=$url;
							}
						}
						$updata=["productinfo"=>json_encode($productinfo)];
						$this->siteorder_model->update($po["id"],$updata);
					}
				}

				$sp=$this->siteproduct_model->getsitepro($order["siteid"],$rid);
				if($sp)
				{
					$this->siteproduct_model->update($sp["id"],["source"=>$url]);					
				}
				echo json_encode(["ok"=>1]);
				die();

			}

		}
	}

	function go($oid)
	{
		$rid=$this->input->get("rid");
		if($rid)
		{
			$order=$this->siteorder_model->getitembyid($oid);
			if($order)
			{
				$sp=$this->siteproduct_model->getsitepro($order["siteid"],$rid);
				if($sp && $sp["source"])
				{
					$url=$sp["source"];
				}
				else
				{
					if($sp)
					{
						$qname=$sp["title"];
					}
					$productinfo=json_decode($order["productinfo"],true);
					foreach($productinfo as $pro)
					{
						if($pro["rid"]==$rid)
						{
							$qname=$pro["name"];
							break;
						}
					}
			
					$url="https://cn.bing.com/search?q=".urlencode($qname)."&ensearch=1";
				}
				header('Location: '.$url);
				die();
			}
		}
	}


	function exportsf()
	{
		$orders=$this->sf_model->getolist();
        if($orders)
        {
			$config = $this->systemconfig_model->get_configs(); 
            $this->load->library('trackingmore',['api'=>$config["trackapikey"]]);
            foreach($orders as $sf)
            {
                $order=$this->siteorder_model->getitembyid($sf["orderid"]);
                $tracking_num=$sf["sfordersn"];
                $carrier="sfb2c";
                $extra=[
                    "customer_email"=>$order["email"],
                    "order_id"=>$order["ordersn"],
                ];
                $result = $this->trackingmore->createTracking($carrier,$tracking_num,$extra);                
                if($result["meta"]["code"]!="200")
                {
                    break;
                }
            }
        }
        die("ok");
	}

	function getxlsxlist()
	{
		ini_set("memory_limit","200M");
		$dirpath='./upload/tmp/'.date("Ym")."/";
		mkdirs($dirpath);
		$config['upload_path']      = $dirpath;
		$config['allowed_types']    = ['xlsx'];
		$config['file_name'] = uniqid();
		$this->load->library('upload', $config);
		$result = $this->upload->do_upload('file');
		$res = array();
		if($result)
		{
			$info = $this->upload->data();
			$inputFileName=$dirpath.$info["orig_name"]; 
			$readcol = ["A","B","C"];
			$myFilter = new MyReadFilter($readcol);
			$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
			$reader->setReadFilter($myFilter);
			$spreadsheet = $reader->load($inputFileName);
			$sheet = $spreadsheet->getActiveSheet();
			foreach ($sheet->getRowIterator(2) as $row) {
				$tmp = array();
				$hasval=false;
				foreach ($row->getCellIterator() as $cell) {
					$tmp[] = $cell->getFormattedValue();
					if(!empty($cell->getFormattedValue())) $hasval=true;
				}
				if($hasval) $res[] = $tmp;
			}
			$mosmessage="";
		}
		else
		{
			$mosmessage = $this->upload->display_errors();
		}
		echo json_encode(["data"=>$res,"msg"=>$mosmessage]);
	}

}


class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{
    private $columns  = [];
    public function __construct($columns) {
        $this->columns  = $columns;
    }

    public function readCell($column, $row, $worksheetName = '') {
        if (in_array($column,$this->columns)) {
            return true;
        }
        return false;
    }
}
